/*
@Desc : 2019/6/29 15:31 
@Version : 1.0.0
@Time : 2019/6/29 15:31 
@Author : hammercui
@File : customJson
@Company: Sdbean
*/
package http

import (
	"encoding/json"
	"github.com/pkg/errors"
	"net/http"
)
var jsonContentType = []string{"application/json; charset=utf-8"}

type CustomJSON struct {
	Data    interface{} `json:"data"`
}

func writeJSON(w http.ResponseWriter, obj interface{}) (err error) {
	var jsonBytes []byte
	writeContentType(w, jsonContentType)
	if jsonBytes, err = json.Marshal(obj); err != nil {
		err = errors.WithStack(err)
		return
	}
	if _, err = w.Write(jsonBytes); err != nil {
		err = errors.WithStack(err)
	}
	return
}

func writeContentType(w http.ResponseWriter, value []string) {
	header := w.Header()
	if val := header["Content-Type"]; len(val) == 0 {
		header["Content-Type"] = value
	}
}
// Render (JSON) writes data with json ContentType.
func (r CustomJSON) Render(w http.ResponseWriter) error {
	return writeJSON(w, r.Data)
}

// WriteContentType write json ContentType.
func (r CustomJSON) WriteContentType(w http.ResponseWriter) {
	writeContentType(w, jsonContentType)
}